package com.suntoon.framework.service.impl;

import com.suntoon.framework.common.Constants;
import com.suntoon.framework.common.response.ResultBO;
import com.suntoon.framework.entity.UserInfo;
import com.suntoon.framework.service.UserService;
import com.suntoon.framework.util.Base64Util;
import com.suntoon.framework.util.JwtTokenUtil;
import com.suntoon.framework.util.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: LEAVES
 * @Version 1.0
 * @Date: 2021年06月25日 09时34分33秒
 * @Description:
 */
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public ResultBO login(String username, String password, HttpServletResponse response) {
        if (StringUtils.isEmpty(username) ){
           log.info(" ## 登录账号为空 ##");
           return ResultBO.fail("账号不能为空");
        }
        if(StringUtils.isEmpty(password)){
            log.info(" ## 登录密码为空 ##");
            return ResultBO.fail("密码不能为空");
        }
        SnowflakeIdWorker idWorker = new SnowflakeIdWorker(1,1);
        long nextId = idWorker.nextId();
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(nextId);
        userInfo.setUsername(username);
        userInfo.setPassword(password);
        String userId = Base64Util.encode(String.valueOf(nextId));
        String token = JwtTokenUtil.sign(userId, username);
        redisTemplate.opsForValue().set(username, token, Constants.TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
        response.setHeader(Constants.AUTHORIZATION, token);
        Map<String, Object> map = new HashMap<>();
        map.put("loginInfo", userInfo);
        map.put("token", token);
        return ResultBO.success(map, "登录成功");
    }
}
